package com.hydra.gateway.config;

import cn.hutool.core.util.StrUtil;
import com.hydra.base.common.BaseConstant;
import com.hydra.gateway.commom.AuthConstant;
import com.hydra.gateway.utils.ResponseUtil;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.Payload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Map;

/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 * Created by macro on 2020/6/17.
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String token = exchange.getRequest().getHeaders().getFirst(AuthConstant.AUTHORITY_KEY);
        if (StrUtil.isEmpty(token)) {
            return chain.filter(exchange);
        }

        try {
            //从token中解析用户信息并设置到Header中去
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            Payload payload = jwsObject.getPayload();

            Map<String, Object> map = payload.toJSONObject();
            Object jti = map.get("jti");// JWT唯一标识
            //判断token是否过期
            Boolean isBlack = redisTemplate.hasKey(BaseConstant.AUTH_TOKEN_JWT_LOGOUT_KEY + jti);
            if (Boolean.TRUE.equals(isBlack)) {
                return ResponseUtil.writeResponseMono(request, response, HttpStatus.UNAUTHORIZED, "logout");
            }

//            String userStr = payload.toString();
//            log.info("AuthGlobalFilter.filter() user:{}",userStr);
            ServerHttpRequest serverHttpRequest = request.mutate()
//                    .header("payload", userStr)
                    .build();
            exchange = exchange.mutate().request(serverHttpRequest).build();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}